package com.titanrise.crm.common.utils;

import java.util.function.Function;

public class EitherPipeUtil {
    public static <L, R1, R2> Function<Either<L, R1>, Either<L, R2>> map(Function<R1, R2> fn) {
        return (either) -> {
            if (either.isLeft()) {
                return Either.left(either.getLeft());
            } else {
                R1 right = either.getRight();
                return Either.right(fn.apply(right));
            }
        };
    }

    public static <L1, L2, R> Function<Either<L1, R>, Either<L2, R>> mapLeft(Function<L1, L2> fn) {
        return (either) -> {
            if (either.isLeft())
                return Either.left(fn.apply(either.getLeft()));
            else
                return Either.right(either.getRight());
        };
    }

    public static <L, R1, R2> Function<Either<L, R1>, Either<L, R2>> flatMap(Function<R1, Either<L, R2>> fn) {
        return (either) -> {
            if (either.isLeft()) {
                return Either.left(either.getLeft());
            } else {
                R1 right = either.getRight();
                return fn.apply(right);
            }
        };
    }

    public static <L, R> Function<Either<L, R>, R> getOrElse(Function<L, R> fn) {
        return (either) -> {
            if (either.isLeft())
                return fn.apply(either.getLeft());
            else
                return either.getRight();
        };
    }
}
